package main

import (
	"fmt"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v9"
	goredislib "github.com/redis/go-redis/v9"
	"sync"
)

func main() {
	client := goredislib.NewClient(&goredislib.Options{
		Addr:     "localhost:6379",
		Password: "",
	})
	pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)
	rs := redsync.New(pool)

	goodsId := 1
	var goodsNum int = 3
	cacheKey := fmt.Sprintf("ksd:goods:order:%d", goodsId)
	mutex := rs.NewMutex(cacheKey)

	waitGroup := sync.WaitGroup{}
	waitGroup.Add(goodsNum)
	var i int = 0
	for i = 0; i < goodsNum; i++ {
		go func(num int) {
			defer waitGroup.Done()
			fmt.Println(num, "加锁成功!!!")
			if err := mutex.Lock(); err != nil {
				panic(err)
			}
			fmt.Println(num, "执行商品扣减库存的业务!!!")
			if ok, err := mutex.Unlock(); !ok || err != nil {
				panic("unlock failed")
			}
			fmt.Println(num, "释放锁成功!!!")
		}(i)
	}
	waitGroup.Wait()
}
